import PlusOutlined from "@ant-design/icons/PlusOutlined"
import { InventoryStatus, ProductQuery, ProductService, ProductStatus } from "@mallfoundry/catalog"
import { Card, Col, Row, Statistic } from "antd"
import * as React from "react"
import { useEffect, useState } from "react"
import { Link, useParams } from "react-router-dom"


const ACTIVE_STATUSES = [ProductStatus.Active]
const ACTIVE_STATUS_VALUES = ACTIVE_STATUSES.join(",")
const ARCHIVED_STATUSES = [ProductStatus.Archived, ProductStatus.Disapproved, ProductStatus.Pending]
const ARCHIVED_STATUS_VALUES = ARCHIVED_STATUSES.join(",")
const OUT_OF_STOCK_INVENTORY_STATUSES = [InventoryStatus.OutOfStock]
const OUT_OF_STOCK_INVENTORY_STATUS_VALUES = OUT_OF_STOCK_INVENTORY_STATUSES.join(",")

function useProductCount(storeId: string, statuses: any[]) {
  const [count, setCount] = useState(0)
  useEffect(() => {
    ProductService.countProducts(new ProductQuery().toBuilder()
      .storeId(storeId).statuses(statuses).build())
      .then(setCount)
  }, [storeId, statuses])
  return count
}

function useInventoryProductCount(storeId: string, statuses: any[]) {
  const [count, setCount] = useState(0)
  useEffect(() => {
    ProductService.countProducts(new ProductQuery().toBuilder()
      .storeId(storeId).inventoryStatuses(statuses).build())
      .then(setCount)
  }, [storeId, statuses])
  return count
}

interface RouterParams {
  storeId: string
}

export function TotalProductQuantity() {
  const { storeId } = useParams<RouterParams>()
  const activeProductCount = useProductCount(storeId, ACTIVE_STATUSES)
  const archivedProductCount = useProductCount(storeId, ARCHIVED_STATUSES)
  const outOfStockProductCount = useInventoryProductCount(storeId, OUT_OF_STOCK_INVENTORY_STATUSES)

  return (
    <Card title="商品管理" size="small" extra={<Link to={`products`}>查看更多</Link>}>
      <Row style={{ textAlign: "center" }} gutter={[16, 16]} justify="center" align="middle">
        <Col span={6}>
          <Link to={{ pathname: `products`, search: `statuses=${ACTIVE_STATUS_VALUES}` }}>
            <Statistic title="在售中" value={activeProductCount}/>
          </Link>
        </Col>
        <Col span={6}>
          <Link to={{ pathname: `products`, search: `statuses=${ARCHIVED_STATUS_VALUES}` }}>
            <Statistic title="在仓库" value={archivedProductCount}/>
          </Link>
        </Col>
        <Col span={6}>
          <Link to={{ pathname: `products`, search: `inventory_statuses=${OUT_OF_STOCK_INVENTORY_STATUS_VALUES}` }}>
            <Statistic title="已售罄" value={outOfStockProductCount}/>
          </Link>
        </Col>
        <Col span={6}>
          <Link to={`products/new`}>
            <PlusOutlined style={{ fontSize: "22px" }}/>
            <div>发布新商品</div>
          </Link>
        </Col>
      </Row>
    </Card>
  )
}
